﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WinformDevFramework.Core.Winform;
using WinformDevFramework.IServices;
using WinformDevFramework.Services;
using WinformDevFramework.Common;
using WinformDevFramework.Models.Common;
using WinformDevFramework.Pages;
using System.Linq.Expressions;
using System.Text.RegularExpressions;

namespace WinformDevFramework
{
    public partial class FrmSupplier : BaseForm1
    {
        private Iw_SupplierServices _iwSupplierServices;

        // 构造函数，注入服务
        public FrmSupplier(Iw_SupplierServices iwSupplierServices)
        {
            _iwSupplierServices = iwSupplierServices;
            InitializeComponent();
        }

        // 初始化页面
        public override void Init()
        {
            base.Init();
            // 初始化数据，默认显示第一页
            var data = GetData(string.Empty, 1, _pageSize);
            this.dataGridViewList.DataSource = data.Items;

            // 设置列标题
            SetColumnHeaders();

            // 初始化分页控件状态
            UpdatePaginationControls(data.TotalCount);

            SetToolButtonStatus(formStatus);
            SetToolsButton();
        }

        // 设置列标题
        private void SetColumnHeaders()
        {
            this.dataGridViewList.Columns["SupplierName"]!.HeaderText = "名称";
            this.dataGridViewList.Columns["ContactPerson"]!.HeaderText = "联系人";
            this.dataGridViewList.Columns["PhoneNumber"].HeaderText = "手机号码";
            this.dataGridViewList.Columns["Email"]!.HeaderText = "邮箱";
            this.dataGridViewList.Columns["BeginPay"]!.HeaderText = "期初应付";
            this.dataGridViewList.Columns["EndPay"].HeaderText = "期末应付";
            this.dataGridViewList.Columns["TaxtRate"]!.HeaderText = "税率";
            this.dataGridViewList.Columns["SortOrder"]!.HeaderText = "排序";
            this.dataGridViewList.Columns["Status"].HeaderText = "状态";
            this.dataGridViewList.Columns["Faxing"]!.HeaderText = "传真";
            this.dataGridViewList.Columns["Address"]!.HeaderText = "地址";
            this.dataGridViewList.Columns["Bank"].HeaderText = "开户行";
            this.dataGridViewList.Columns["SupplierCode"].HeaderText = "供应商编码";
            this.dataGridViewList.Columns["TaxpayerNumber"]!.HeaderText = "纳税人识别号";
            this.dataGridViewList.Columns["BankAccount"]!.HeaderText = "银行账号";
            this.dataGridViewList.Columns["LandlinePhone"].HeaderText = "固定电话";
            this.dataGridViewList.Columns["Remark"].HeaderText = "备注";
            this.dataGridViewList.Columns["TotalPayable"]!.HeaderText = "应付款总额";
            this.dataGridViewList.Columns["TotalAmountReturned"].HeaderText = "退货款总额";
            this.dataGridViewList.Columns["TotalAmountPaid"].HeaderText = "已结款总额";
            this.dataGridViewList.Columns["TotalAmountOutstanding"].HeaderText = "未结款总额";
        }

        // 双击数据行事件
        public override void DataGridViewListDoubleClick(object? sender, DataGridViewCellEventArgs e)
        {
            base.DataGridViewListDoubleClick(sender, e);
            var g = (DataGridView)sender;
            var model = g.CurrentRow.DataBoundItem as w_Supplier;
            // 给详情页设置数据
            this.txtID.Text = model.ID.ToString();
            txtSupplierName.Text = model.SupplierName;
            SupplierCode.Text = model.SupplierCode;
            txtContactPerson.Text = model.ContactPerson;
            txtPhoneNumber.Text = model.PhoneNumber;
            txtEmail.Text = model.Email;
            txtBeginPay.Value = model.BeginPay ?? 0;
            txtEndPay.Value = model.EndPay ?? 0;
            txtTaxtRate.Value = model.TaxtRate ?? 0;
            txtSortOrder.Text = model.SortOrder.ToString();
            checkBox1.Checked = model.Status.Value;
            txtFaxing.Text = model.Faxing;
            txtAddress.Text = model.Address;
            txtBank.Text = model.Bank;
            txtTaxpayerNumber.Text = model.TaxpayerNumber;
            txtBankAccount.Text = model.BankAccount;
            txtLandlinePhone.Text = model.LandlinePhone;
            TotalPayable.Text = model.TotalPayable.ToString();
            TotalAmountReturned.Text = model.TotalAmountReturned.ToString();
            TotalAmountPaid.Text = model.TotalAmountPaid.ToString();
            TotalAmountOutstanding.Text = model.TotalAmountOutstanding.ToString();
            txtRemark.Text = model.Remark;
            //TODO设置tab页数据

            SetToolButtonStatus(formStatus);
        }

        // 添加按钮点击事件
        public override void AddFunction(object sender, EventArgs e)
        {
            base.AddFunction(sender, e);
            SetToolButtonStatus(formStatus);
        }

        // 编辑按钮点击事件
        public override void EditFunction(object sender, EventArgs e)
        {
            base.EditFunction(sender, e);
            SetToolButtonStatus(formStatus);
            SupplierCode.ReadOnly = true;
        }

        // 保存按钮点击事件
        public override void SaveFunction(object sender, EventArgs e)
        {
            base.SaveFunction(sender, e);

            try
            {
                // 1. 数据验证
                var validationErrors = ValidateInputs();
                if (validationErrors.Any())
                {
                    MessageBox.Show($"请修正以下错误：\n{string.Join("\n", validationErrors)}", "验证错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                // 2. 准备模型数据
                var model = PrepareSupplierModel();

                // 3. 执行保存操作
                bool isSuccess;
                if (string.IsNullOrEmpty(txtID.Text))
                {
                    var id = _iwSupplierServices.Insert(model);
                    isSuccess = id > 0;
                    if (isSuccess) txtID.Text = id.ToString();
                }
                else
                {
                    model.ID = int.Parse(txtID.Text);
                    isSuccess = _iwSupplierServices.Update(model);
                }

                // 4. 处理结果
                if (isSuccess)
                {
                    MessageBox.Show("保存成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    RefreshDataGrid();
                    SetToolButtonStatus(formStatus);
                }
                else
                {
                    MessageBox.Show("保存失败，请重试或联系管理员", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存过程中发生错误：{ex.Message}", "系统错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        // 验证输入
        private List<string> ValidateInputs()
        {
            var errors = new List<string>();

            if (string.IsNullOrWhiteSpace(txtSupplierName.Text))
                errors.Add("供应商名称不能为空");

            if (string.IsNullOrWhiteSpace(txtContactPerson.Text))
                errors.Add("联系人不能为空");

            if (string.IsNullOrWhiteSpace(txtPhoneNumber.Text))
                errors.Add("手机号码不能为空");
            else if (!Regex.IsMatch(txtPhoneNumber.Text, @"^1[3-9]\d{9}$"))
                errors.Add("手机号码格式不正确");

            if (string.IsNullOrWhiteSpace(txtEmail.Text))
                errors.Add("邮箱不能为空");
            else if (!Regex.IsMatch(txtEmail.Text, @"^[^@\s]+@[^@\s]+\.[^@\s]+$"))
                errors.Add("邮箱格式不正确");

            if (string.IsNullOrWhiteSpace(SupplierCode.Text))
                errors.Add("供应商编码不能为空");

            return errors;
        }

        // 准备供应商模型
        private w_Supplier PrepareSupplierModel()
        {
            return new w_Supplier
            {
                SupplierName = txtSupplierName.Text.Trim(),
                ContactPerson = txtContactPerson.Text.Trim(),
                PhoneNumber = txtPhoneNumber.Text.Trim(),
                Email = txtEmail.Text.Trim(),
                BeginPay = txtBeginPay.Value,
                EndPay = txtEndPay.Value,
                TaxtRate = txtTaxtRate.Value,
                SortOrder = int.TryParse(txtSortOrder.Text, out var sortOrder) ? sortOrder : 1,
                Status = checkBox1.Checked,
                Faxing = txtFaxing.Text.Trim(),
                Address = txtAddress.Text.Trim(),
                Bank = txtBank.Text.Trim(),
                TaxpayerNumber = txtTaxpayerNumber.Text.Trim(),
                BankAccount = txtBankAccount.Text.Trim(),
                LandlinePhone = txtLandlinePhone.Text.Trim(),
                Remark = txtRemark.Text.Trim(),
                SupplierCode = SupplierCode.Text.Trim()
            };
        }

        // 刷新数据网格
        private void RefreshDataGrid()
        {
            this.dataGridViewList.DataSource = GetData(string.Empty, 1, _pageSize);
        }

        // 取消按钮点击事件
        public override void CanelFunction(object sender, EventArgs e)
        {
            bool isAdd = formStatus == FormStatus.Add;
            base.CanelFunction(sender, e);
            SetToolButtonStatus(formStatus);
            btnEdit.Enabled = !isAdd;
            btnDel.Enabled = !isAdd;
        }

        // 删除按钮点击事件
        public override void DelFunction(object sender, EventArgs e)
        {
            base.DelFunction(sender, e);
            var result = MessageBox.Show("是否删除？", "确认", MessageBoxButtons.YesNoCancel);
            if (result == DialogResult.Yes)
            {
                _iwSupplierServices.DeleteById(Int32.Parse(txtID.Text));
                formStatus = FormStatus.Del;
                SetToolButtonStatus(formStatus);
                // 修正调用方式
                this.dataGridViewList.DataSource = GetData(string.Empty, 1, _pageSize);
            }
        }

        // 导入按钮点击事件
        public override void ImportFunction(object sender, EventArgs e)
        {
            base.ImportFunction(sender, e);

            try
            {
                using (var ofd = new System.Windows.Forms.OpenFileDialog
                {
                    Title = "选择供应商Excel文件",
                    InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
                    Filter = "Excel文件 (*.xlsx, *.xls)|*.xlsx;*.xls|所有文件 (*.*)|*.*",
                    ValidateNames = true,
                    CheckFileExists = true,
                    CheckPathExists = true
                })
                {
                    if (ofd.ShowDialog() != DialogResult.OK) return;

                    using (var progressForm = new ProgressForm("正在导入供应商数据..."))
                    {
                        progressForm.Show();

                        var filePath = ofd.FileName;
                        DataTable dataTable;

                        try
                        {
                            dataTable = ExcelHelper.GetExcel(filePath);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show($"读取Excel文件失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }

                        if (dataTable == null || dataTable.Rows.Count == 0)
                        {
                            MessageBox.Show("Excel文件中没有数据！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            return;
                        }

                        var requiredColumns = new[] { "供应商名称", "联系人", "手机号码", "邮件地址", "初期应付", "期末应付", "税率", "排序", "状态", "供应商编码" };
                        var missingColumns = requiredColumns.Where(c => !dataTable.Columns.Contains(c)).ToList();
                        if (missingColumns.Any())
                        {
                            MessageBox.Show($"Excel文件中缺少以下必要列: \n{string.Join("\n", missingColumns)}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }

                        var dataSuppliers = new List<w_Supplier>();
                        var errorMessages = new StringBuilder();
                        int successCount = 0;

                        foreach (DataRow dr in dataTable.Rows)
                        {
                            if (dr.ItemArray.All(item => item == null || string.IsNullOrWhiteSpace(item.ToString()))) continue;

                            var validationErrors = ValidateSupplierRow(dr);
                            if (validationErrors.Any())
                            {
                                errorMessages.AppendLine($"第{dataTable.Rows.IndexOf(dr) + 1}行: {string.Join("; ", validationErrors)}");
                                continue;
                            }

                            try
                            {
                                dataSuppliers.Add(new w_Supplier
                                {
                                    SupplierName = dr["供应商名称"].ToString().Trim(),
                                    ContactPerson = dr["联系人"].ToString().Trim(),
                                    PhoneNumber = dr["手机号码"].ToString().Trim(),
                                    Email = dr["邮件地址"].ToString().Trim(),
                                    BeginPay = decimal.Parse(dr["初期应付"].ToString().Trim()),
                                    EndPay = decimal.Parse(dr["期末应付"].ToString().Trim()),
                                    TaxtRate = int.Parse(dr["税率"].ToString().Trim()),
                                    SortOrder = int.Parse(dr["排序"].ToString().Trim()),
                                    Status = bool.Parse(dr["状态"].ToString().Trim()),
                                    Faxing = dr["传真"]?.ToString().Trim() ?? string.Empty,
                                    Address = dr["地址"]?.ToString().Trim() ?? string.Empty,
                                    Bank = dr["开户行"]?.ToString().Trim() ?? string.Empty,
                                    TaxpayerNumber = dr["纳税人识别号"]?.ToString().Trim() ?? string.Empty,
                                    BankAccount = dr["银行账号"]?.ToString().Trim() ?? string.Empty,
                                    LandlinePhone = dr["固定电话"]?.ToString().Trim() ?? string.Empty,
                                    Remark = dr["备注"]?.ToString().Trim() ?? string.Empty,
                                    SupplierCode = dr["供应商编码"].ToString().Trim()
                                });
                                successCount++;
                            }
                            catch (Exception ex)
                            {
                                errorMessages.AppendLine($"第{dataTable.Rows.IndexOf(dr) + 1}行处理失败: {ex.Message}");
                            }
                        }

                        if (errorMessages.Length > 0)
                        {
                            var result = MessageBox.Show($"发现以下问题:\n{errorMessages.ToString()}\n\n是否继续导入有效数据?", "数据验证警告", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                            if (result != DialogResult.Yes) return;
                        }

                        if (dataSuppliers.Count == 0)
                        {
                            MessageBox.Show("没有有效数据可导入!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return;
                        }

                        var id = _iwSupplierServices.ImportSuppliers(dataSuppliers);
                        if (id > 0)
                        {
                            MessageBox.Show($"成功导入 {successCount} 条供应商数据!", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            SetToolButtonStatus(formStatus);
                            this.dataGridViewList.DataSource = GetData(string.Empty, 1, _pageSize);
                        }
                        else
                        {
                            MessageBox.Show("导入失败，请检查数据或联系管理员!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"导入过程中发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        // 验证供应商数据行
        private List<string> ValidateSupplierRow(DataRow dr)
        {
            var errors = new List<string>();
            var validations = new (string Field, Func<string, bool> Validate, string Error)[]
            {
                ("供应商名称", v =>!string.IsNullOrWhiteSpace(v), "不能为空"),
                ("联系人", v =>!string.IsNullOrWhiteSpace(v), "不能为空"),
                ("手机号码", v => Regex.IsMatch(v?.Trim()?? "", @"^1[3-9]\d{9}$"), "格式不正确"),
                ("邮件地址", v => Regex.IsMatch(v?.Trim()?? "", @"^[^@\s]+@[^@\s]+\.[^@\s]+$"), "格式不正确"),
                ("初期应付", v => decimal.TryParse(v, out _), "必须是数字"),
                ("期末应付", v => decimal.TryParse(v, out _), "必须是数字"),
                ("税率", v => int.TryParse(v, out var rate) && rate >= 0 && rate <= 100, "必须是0-100的整数"),
                ("排序", v => int.TryParse(v, out _), "必须是整数"),
                ("状态", v => bool.TryParse(v, out _), "必须是TRUE/FALSE"),
                ("供应商编码", v =>!string.IsNullOrWhiteSpace(v), "不能为空")
            };

            foreach (var (field, validate, error) in validations)
            {
                var value = dr[field]?.ToString();
                if (!validate(value))
                {
                    errors.Add($"{field}{error}");
                }
            }

            return errors;
        }
        // 查询按钮点击事件
        public override void SearchFunction(object sender, EventArgs e)
        {
            base.SearchFunction(sender, e); 
            LoadData();
        }

        // 下一页按钮点击事件
        public override void NextPageFunction(object sender, EventArgs e)
        {
            base.NextPageFunction(sender, e); 
            LoadData();
        }
        // 上一页按钮点击事件
        public override void PrevPageFunction(object sender, EventArgs e)
        {
            base.PrevPageFunction(sender, e); 
            LoadData();
        }

        //加载数据
        protected override void LoadData()
        {
            string keyword = base.txtSearch.Text.Trim();

            var data = GetData(keyword, _currentPage, _pageSize);
            dataGridViewList.DataSource = data.Items;

            // 更新分页控件
            UpdatePaginationControls(data.TotalCount);
        }
       
        //分页查询模型
        private IPageList<w_Supplier> GetData(string keyword, int pageIndex, int pageSize)
        {
            Expression<Func<w_Supplier, bool>> predicate = null;

            if (!string.IsNullOrEmpty(keyword))
            {
                predicate = s => s.SupplierName.Contains(keyword) ||
                             s.ContactPerson.Contains(keyword) ||
                             s.PhoneNumber.Contains(keyword);
            }

            var result = _iwSupplierServices.QueryPage(
                predicate: predicate,
                orderBy: "Id DESC",
                pageIndex: pageIndex,
                pageSize: pageSize
            );

            return result;
        }


        //用户自定义状态
        public override void SetToolButtonStatus(FormStatus status)
        {

            //if (status == FormStatus.View) // 特殊状态处理
            //{
            //    // 自定义审批状态逻辑
            //    return;
            //}
            base.SetToolButtonStatus(status); // 复用基础逻辑
        }



        //自定义提示
        public override bool ValidateData()
        {
            if (string.IsNullOrEmpty(txtSupplierName.Text))
            {
                MessageBox.Show("字典内容不能为空！");
                return false;
            }
            return true;
        }






        private void TotalAmountPaid_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            tabControl2.SelectedTab = tabPage3;
        }

        private void TotalPayable_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            tabControl2.SelectedTab = tabPage1;
        }

        private void TotalAmountReturned_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            tabControl2.SelectedTab = tabPage2;
        }

        private void TotalAmountOutstanding_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            tabControl2.SelectedTab = tabPage4;
        }


        //导出excel方法
        public override void ExportFunction(object sender, EventArgs e)
        {
            base.ExportFunction(sender, e);

            try
            {
                // 获取数据并创建DataTable
                var suppliers = _iwSupplierServices.Query().ToList();
                var dataTable = new DataTable("供应商数据");

                // 添加列
                string[] columns = { "序号", "供应商名称", "联系人", "手机号码", "邮件地址",
                           "初期应付", "期末应付", "税率", "排序", "状态", "传真",
                           "地址", "开户行", "纳税人识别号", "银行账号", "固定电话",
                           "备注", "供应商编码" };
                Type[] types = { typeof(int), typeof(string), typeof(string), typeof(string), typeof(string),
                        typeof(decimal), typeof(decimal), typeof(decimal), typeof(int), typeof(string),
                        typeof(string), typeof(string), typeof(string), typeof(string), typeof(string),
                        typeof(string), typeof(string), typeof(string) };

                for (int i = 0; i < columns.Length; i++)
                {
                    dataTable.Columns.Add(columns[i], types[i]);
                }

                // 填充数据
                for (int i = 0; i < suppliers.Count; i++)
                {
                    var s = suppliers[i];
                    dataTable.Rows.Add(i + 1, s.SupplierName, s.ContactPerson, s.PhoneNumber, s.Email,
                                      s.BeginPay, s.EndPay, s.TaxtRate, s.SortOrder, s.Status, s.Faxing,
                                      s.Address, s.Bank, s.TaxpayerNumber, s.BankAccount, s.LandlinePhone,
                                      s.Remark, s.SupplierCode);
                }

                // 导出Excel
                ExcelHelper.ExportToExcel(dataTable, $"供应商数据_{DateTime.Now:yyyyMMdd_HHmmss}");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"导出过程中发生错误：\n{ex.Message}", "错误",
                               MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }





    }
}
